package com.example.service;

import com.example.constant.ErrorMessageConstant;
import com.example.constant.MessageTypeConstant;
import com.example.constant.SendReasonConstant;
import com.example.entity.ChargingPile;
import com.example.entity.body.impl.ASDUBody;
import com.example.entity.factory.Unpooled;
import com.example.entity.message.Message;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.AttributeKey;

public class CountHandler extends ChannelInboundHandlerAdapter {

	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		// TODO Auto-generated method stub

		Message message = (Message) msg;

		ASDUBody body = message.getBody();
		Byte type = body.getType();
		ChargingPile state = (ChargingPile) ctx.channel().attr(AttributeKey.valueOf("state")).get();

		if (type == MessageTypeConstant.COUNT_MESSAGE) {
			System.out.println("调用了 CountHandler");
			char reason = body.getSendReason();
			if (reason == SendReasonConstant.AFFIRM) {
				if (state.isCallEnd()) {
					System.out.println("count affirm");
					state.hasCountAffirm();
				} else {
					// TODO 错误处理 未总召结束先计量
					ctx.fireChannelRead(Unpooled.wrapperErrorMessage(ErrorMessageConstant.NO_CALL_END));

				}

			} else if (reason == SendReasonConstant.END) {
				if (state.isCountRespond()) {
					System.out.println("count end");

					ctx.writeAndFlush(Unpooled.newTimeSynMessage());
					state.hasCountEnd();
				} else {
					// TODO 错误处理 未进行计量就结束了
					ctx.fireChannelRead(Unpooled.wrapperErrorMessage(ErrorMessageConstant.NO_COUNT_RESOND));

				}

			}
		} else if (type == MessageTypeConstant.COUNT_NUM_MESSAGE) {
			if (state.isCountAffirm()) {
				System.out.println("count count");
				state.hasCountRespond();
			} else {
				// TODO 错误处理 未计量确认就收到计量
				ctx.fireChannelRead(Unpooled.wrapperErrorMessage(ErrorMessageConstant.NO_COUNT_AFFIRM));

			}

		} else {
			ctx.fireChannelRead(msg);
		}

	}

}
